package com.ems.config;

import com.ems.util.StateEnum;
import com.ems.util.StateException;
import com.ems.vo.BaseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.net.UnknownHostException;

/**
 * @Author: Wuzh
 * @Description:
 * @ControllerAdvice: 这是一个非常有用的注解，顾名思义，这是一个增强的 Controller。使用这个 Controller
 * @Date Created in 22:53 2020/8/18
 * @return
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理自定义的业务异常
     * @param e
     * @ExceptionHandler: 注解用来指明异常的处理类型，即如果这里指定为 NullPointerException，则数组越界异常就不会进到这个方法中来。
     * 拦截所有StateException异常
     */
    @ExceptionHandler (value = StateException.class)
    public BaseResult businessExceptionHandler ( StateException e) {
        log.error ( "发生业务异常 - [{}-{}]", e.getCode (), e.getMessage () );
        return BaseResult.fail ( e.getCode (), e.getMessage () );
    }


    /**
     * 处理其他异常
     * @param e
     */
    @ExceptionHandler (value = NullPointerException.class)
    public BaseResult nullPointerException ( NullPointerException e) {
        log.error ( "未知异常 - [{}]", e );
        return BaseResult.fail ( StateEnum.NULL_POINTER_EXCE );
    }

    /**
     * ModBus请求无法发现主机异常
     * @param e
     * @return
     */
    @ExceptionHandler (value = UnknownHostException.class)
    public BaseResult unknownHostException (UnknownHostException e) {
        log.error ( "ModBus主机失联 - [{}]", e );
        return BaseResult.fail ( StateEnum.UNKNOW_HOST_EXCE );
    }

    /**
     * 系统发生无法甄别的异常
     * @param e
     * @return
     */
    @ExceptionHandler (value = Exception.class)
    public BaseResult exceptionHandler (NullPointerException e) {
        log.error ( "未知异常 - [{}]", e );
        return BaseResult.fail ( StateEnum.ERROR );
    }

}
